package com.xiechuang.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 类助手
 * @Author: xiechuang
 * @Date: 2023/1/11
 */
public class ClassHelper {

    private static final Logger logger = LoggerFactory.getLogger(ClassHelper.class);
    private static final String CLASS_NAME = ClassHelper.class.getName();

    private static final Map<String, Class<?>> commonClassCache = new HashMap(32);

    // 反射获取类 原型
    @SuppressWarnings("unchecked")
    public static Class forName(String className) {
        Class claz = commonClassCache.get(className);
        if (commonClassCache.containsKey(className)) {
            return claz;
        } else {
            try {
                claz = Class.forName(className);
            } catch (ClassNotFoundException e) {
            }
            commonClassCache.put(className, claz);
            return claz;
        }
    }

    public static boolean exists(String className) {
        return null != forName(className);
    }

    /**
     * 反射 实例化
     *
     * @param className
     * @return
     */
    public static Object newInstance(String className) {
        try {
            return forName(className).newInstance();
        } catch (Exception ex) {
            logger.error(CLASS_NAME + "：", ex);
        }
        return null;
    }

}